package com.imhuis.pay.applet.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.imhuis.pay.applet.IAppletService;
import com.imhuis.pay.applet.WxResolvePhoneFormDTO;
import com.imhuis.pay.service.handler.WeChatOpenIdByJsCodeLoader;
import com.imhuis.pay.utils.WxResolveDataUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AppletServiceImpl implements IAppletService {

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private WeChatOpenIdByJsCodeLoader weChatOpenIdByJsCodeLoader;


    /**
     * 解析加密手机
     * @param wxResolvePhoneFormDTO
     * @return
     */
    private String decryptPhone(WxResolvePhoneFormDTO wxResolvePhoneFormDTO) {

        WeChatOpenIdByJsCodeLoader.WxLoginResult wxLoginResult = weChatOpenIdByJsCodeLoader.load(wxResolvePhoneFormDTO.getJsCode());
        String sessionKey = wxLoginResult.getSessionKey();

        // 解析encrypted data获取用户手机号（包括openid）
        try {
            String resolveData = new String(WxResolveDataUtils.decrypt(wxResolvePhoneFormDTO.getEncryptedData(), sessionKey, wxResolvePhoneFormDTO.getIv()));
            /*{"phoneNumber":"11111111111","purePhoneNumber":"11111111111","countryCode":"86","watermark":{"timestamp":1554949910,"appid":"wxc418d44a80e38c7b"}}*/
            JsonNode jsonNode = objectMapper.readTree(resolveData);
            return jsonNode.get("phoneNumber").asText();
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return "";
    }

}
